package com.xoa.service.schedule.impl;

import com.xoa.dao.common.SysCodeMapper;
import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.meet.MeetingRoomMapper;
import com.xoa.dao.schedule.ScheduleMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.model.calender.Calendar;
import com.xoa.model.common.SysCode;
import com.xoa.model.meet.MeetingRoomWithBLOBs;
import com.xoa.model.schedule.ResultLeaderActivity;
import com.xoa.model.schedule.Schedule;
import com.xoa.model.schedule.ScheduleModel;
import com.xoa.model.sms.SmsBody;
import com.xoa.model.users.Users;
import com.xoa.service.calendar.CalendarService;
import com.xoa.service.schedule.ScheduleService;
import com.xoa.service.sms.SmsService;
import com.xoa.util.CookiesUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.L;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.common.wrapper.BaseWrapper;
import com.xoa.util.dataSource.ContextHolder;
import com.xoa.util.page.PageParams;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * Created by 程叶同 on 2017-10-07.
 * 保存领导活动安排
 */

@Service
public class ScheduleServiceImpl implements ScheduleService {

    @Resource
    private ScheduleMapper scheduleDao;
    @Resource
    private UsersMapper userdao;
    @Resource
    DepartmentMapper departmentMapper;
    @Resource
    ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Resource
    UsersMapper usersMapper;

    @Resource
    SysCodeMapper sysCodeMapper;

    @Resource
    SmsService smsService;
    @Resource
    MeetingRoomMapper meetingRoomMapper;
    @Resource
    private CalendarService calendarService;

    @Override
    public ToJson<ScheduleModel> saveSchedule(HttpServletRequest request, ScheduleModel schedule) {
        ToJson<ScheduleModel> json = new ToJson<ScheduleModel>();
        try {
            schedule.setStatus("0");
            Date date = new Date(schedule.getBegin_time());
            long beginTimes=date.getTime();
            schedule.setBegin_time(beginTimes);
            Date date1 = new Date(schedule.getEnd_time());
            long endTimes=date1.getTime();
            schedule.setEnd_time(endTimes);
            int count = scheduleDao.saveSchedule(schedule);
            if (count > 0) {
                addAffairs(schedule, request);
                //将新建的领导活动添加到日程
                Calendar calendar=new Calendar();
                calendar.setContent("领导活动："+schedule.getSubject());//日程内容
                calendar.setCalType("1");//日程类型：工作事务
                if(schedule.getBegin_time()!=null){ //开始时间

                    String beginTime=String.valueOf(schedule.getEnd_time()/1000);
                    calendar.setCalTime(Integer.valueOf(beginTime));
                }
                if(schedule.getEnd_time()!=null){   //结束时间
                    String endTime=String.valueOf(schedule.getEnd_time()/1000);
                    calendar.setEndTime(Integer.valueOf(endTime));

                }
                calendar.setAddTime(new Date());    //新建日程时间
                Cookie redisSessionId = CookiesUtil.getCookieByName(request,"redisSessionId");
                Users user = SessionUtils.getSessionInfo(request.getSession(),Users.class,new Users(),redisSessionId);
                calendar.setUserId(user.getUserId());
                calendar.setCalLevel("1");
               calendar.setBeforeRemaind("0|0|0");
                String[] takerArray=schedule.getAttendee().split(",");
                StringBuffer takerStr=new StringBuffer();
                for(String userid:takerArray){
                    if(!StringUtils.checkNull(userid)){
                        Users userTemp=usersMapper.findUsersByuserId(userid);
                        if(userTemp!=null){
                            if(!StringUtils.checkNull(userTemp.getUserId())){
                                takerStr.append(userTemp.getUserId()+",");
                            }
                        }
                    }
                }
                calendar.setTaker(takerStr.toString());
                calendarService.insertSelective(calendar,request);
                json.setMsg("创建成功");
                json.setFlag(0);
            }

        } catch (Exception e) {
            json.setMsg(e.getMessage());
            L.e("ScheduleModelServiceImpl saveScheduleModel:" + e);
        }
        return json;
    }

    @Override
    public ToJson<ScheduleModel> updateSchedule(HttpServletRequest request, Schedule schedule) {
        ToJson<ScheduleModel> json = new ToJson<ScheduleModel>();
        try {
            int count= scheduleDao.updateByPrimaryKeySelective(schedule);
            //int count = scheduleDao.updateSchedule(schedule);
            if (count > 0) {
                json.setMsg("修改成功");
                json.setFlag(0);
            }
        } catch (Exception e) {
            json.setMsg(e.getMessage());
            L.e("ScheduleServiceImpl updateSchedule:" + e);
        }
        return json;
    }

    @Override
    public ToJson<ScheduleModel> selectScheduleById(HttpServletRequest request, Integer id) {
        ToJson<ScheduleModel> json = new ToJson<ScheduleModel>();
        ResultLeaderActivity res=new ResultLeaderActivity();
        SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
        try {
          //  ScheduleModel schedule = scheduleDao.selectScheduleById(id);
            Schedule schedule=scheduleDao.selectByPrimaryKey(id);
            String departName = departmentMapper.departmentOneSelect(Integer.parseInt(schedule.getUndertake()));
            if (departName == null) {
                departName = "";
            }
            //出席领导
            String leader = schedule.getLeader();
            String leaderName = "";
            if (leader != null && leader != "") {
                String[] leades = leader.split(",");
                for (int i=0;i<leades.length;i++) {
                    String usernameByUserId = userdao.getUsernameByUserId(leades[i]);
                    leaderName += usernameByUserId + ",";
                }
                if (leaderName.length() > 0) {
                    leaderName = leaderName.substring(0, leaderName.length() - 1);
                }
            }
            //出席人员
            String attentees = schedule.getAttendee();
            String[] split = attentees.split(",");
            String attenteeNames = "";
            if (split != null && split.length > 0) {
                for (String s : split) {
                    String name = userdao.getUsernameByUserId(s);
                    if (name != null && name != "") {
                        attenteeNames = attenteeNames + name + ",";
                    }
                }
            }
            if (attenteeNames.length() > 0) {
                attenteeNames = attenteeNames.substring(0, attenteeNames.length() - 1);
            }
            //会议室
            MeetingRoomWithBLOBs meetingRoomWithBLOBs = meetingRoomMapper.selectByPrimaryKey(schedule.getRoomId());
            //String userName = userdao.getUsernameById(schedule.getCreate_user());
            Users users = userdao.getUsersByUid(schedule.getCreateUser());
            res.setId(schedule.getId());
            res.setAttenteeId(schedule.getAttendee());
            res.setUndertakeId(schedule.getUndertake());
            res.setBeginTimeStr(sdf.format(new Date(schedule.getBeginTime())));
            res.setEndTimeStr(sdf.format(new Date(schedule.getEndTime())));
            res.setScheduleType(schedule.getScheduleType());
            res.setSubject(schedule.getSubject());
            res.setAppUser(users.getUserName());
            res.setCreateUserId(users.getUid());
            res.setLeader(leaderName);
            //res.setStatus(status);
            res.setUndertake(departName);
            res.setLocation(schedule.getLocation());
            res.setAttentee(attenteeNames);
            res.setRemark(schedule.getRemark());
            res.setLeaderId(schedule.getLeader());
            if (meetingRoomWithBLOBs != null) {
                Integer sid = meetingRoomWithBLOBs.getSid();
                res.setRoomId(String.valueOf(sid));
                res.setRoomName(meetingRoomWithBLOBs.getMrName());
            }else{
                res.setRoomName("");
                res.setRoomId("");
            }


            if (schedule != null) {
                json.setObject(res);
                json.setMsg("详情获取成功");
                json.setFlag(0);
            }
        } catch (Exception e) {
            json.setMsg(e.getMessage());
            L.e("ScheduleServiceImpl selectScheduleById:" + e);
        }
        return json;
    }

    @Override
    public ToJson<ScheduleModel> deleteScheduleById(HttpServletRequest request, Integer id) {
        ToJson<ScheduleModel> json = new ToJson<ScheduleModel>();
        try {
            scheduleDao.deleteScheduleById(id);
            json.setMsg("删除数据成功");
            json.setFlag(0);
        } catch (Exception e) {
            json.setMsg(e.getMessage());
            L.e("ScheduleServiceImpl deleteScheduleById:" + e);
        }
        return json;
    }

    @Override
    public ToJson<ScheduleModel> commitSchedule(int id) {
        ToJson<ScheduleModel> json = new ToJson<ScheduleModel>();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", id);
        map.put("status", 1);
        int count = scheduleDao.commitSchedule(map);
        if (count > 0) {
            json.setMsg("已提交");
            json.setFlag(0);
        }
        return json;
    }

    @Override
    public ToJson<ResultLeaderActivity> queryLeaderActiveAll(HttpServletRequest request, ScheduleModel schedules, Integer page, Integer pageSize, boolean useFlag, String query) {
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
        ToJson<ResultLeaderActivity> json = new ToJson<ResultLeaderActivity>();
        List<ResultLeaderActivity> result = new ArrayList<ResultLeaderActivity>();
        Map<String, Object> map = new HashMap<String, Object>();
        ResultLeaderActivity res = null;
        PageParams pageParams = new PageParams();
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        pageParams.setUseFlag(useFlag);
        SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
        map.put("pageParams", pageParams);
        if (!"query".equals(query)) {
            //权限判断  系统管理员可看全部
            if (users.getUserPriv().intValue() != 1) {
                schedules.setCreate_user(users.getUid());
            }
        }
        map.put("schedule", schedules);
        //日期类型转换
//        if(schedules.getBegin_time()!=null){
//            schedules.setBegin_time(DateFormat.getDate(String.valueOf(schedules.getBegin_time())).getTime());
//        }
//        if(schedules.getEnd_time()!=null){
//            schedules.setEnd_time(DateFormat.getDate(String.valueOf(schedules.getEnd_time())).getTime());
//        }
//        if(schedules.getCreate_time()!=null){
//            schedules.setCreate_time(DateFormat.getDate(String.valueOf(schedules.getCreate_time())).getTime());
//        }
        List<ScheduleModel> list = scheduleDao.queryLeaderActiveAll(map);
        if (list != null) {
            for (ScheduleModel schedule : list) {
                res = new ResultLeaderActivity();
                /*Date d=new Date(schedule.getBegin_time());
                String date=sdf.format(d);
                String datex=date.substring(5,10);
                String date2=date.substring(11,16);*/
                String schedule_type = schedule.getSchedule_type();
                //承办单位
                if (schedule.getUndertake().endsWith(",")) {
                    String undertake = schedule.getUndertake();
                    schedule.setUndertake(undertake.substring(0,undertake.length()-1));
                }
                String departName = departmentMapper.departmentOneSelect(Integer.parseInt(schedule.getUndertake()));
                if (departName == null) {
                    departName = "";
                }
                //出席领导
                String leader = schedule.getLeader();
                String leaderName = "";
                if (leader != null && leader != "") {
                    String[] leades = leader.split(",");
                    for (String l : leades) {
                        String usernameByUserId = userdao.getUsernameByUserId(schedule.getLeader());
                        leaderName += usernameByUserId + ",";
                    }
                    if (leaderName.length() > 0) {
                        leaderName = leaderName.substring(0, leaderName.length() - 1);
                    }
                }
                //出席人员
                String attentees = schedule.getAttendee();
                String[] split = attentees.split(",");
                String attenteeNames = "";
                if (split != null && split.length > 0) {
                    for (String s : split) {
                        String name = userdao.getUsernameByUserId(s);
                        if (name != null && name != "") {
                            attenteeNames = attenteeNames + name + ",";
                        }
                    }
                }
                if (attenteeNames.length() > 0) {
                    attenteeNames = attenteeNames.substring(0, attenteeNames.length() - 1);
                }
                String userName = userdao.getUsernameById(schedule.getCreate_user());
                /*String status=schedule.getStatus();
                   int num=Integer.parseInt(status);
                   if(0==num){
                       status="未审批";
                   }
                   if(1==num){
                       status="已审批";
                   }*/
                   /* int hours=d.getHours();
                    String str=null;
                    if(hours>12){
                        str="下午";
                    }else{
                        str="上午";
                    }*/
//                    res.setId(schedule.getId());
//                    res.setDate(datex);
//                    res.setDateAmong(str);
//                    res.setTime(date2);
                res.setId(schedule.getId());
                res.setAttenteeId(schedule.getAttendee());
                res.setUndertakeId(schedule.getUndertake());
                res.setBeginTimeStr(sdf.format(new Date(schedule.getBegin_time())));
                res.setEndTimeStr(sdf.format(new Date(schedule.getEnd_time())));
                res.setScheduleType(schedule_type);
                res.setSubject(schedule.getSubject());
                res.setAppUser(userName);
                res.setLeader(leaderName);
                //res.setStatus(status);
                res.setUndertake(departName);
                res.setLocation(schedule.getLocation());
                res.setAttentee(attenteeNames);
                res.setRemark(schedule.getRemark());
                result.add(res);
            }
            json.setTotleNum(pageParams.getTotal());
        }
        if (result != null) {
            json.setObj(result);
            json.setMsg("ok");
            json.setFlag(0);
        }
        return json;
    }


    @Override
    public ToJson<ResultLeaderActivity> queryLeaderActiveMe(ScheduleModel schedules, HttpServletRequest request) {
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
        ToJson<ResultLeaderActivity> json = new ToJson<ResultLeaderActivity>();
        List<ResultLeaderActivity> result = new ArrayList<ResultLeaderActivity>();
        Map<String, Object> map = new HashMap<String, Object>();
        ResultLeaderActivity res = null;
        SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm");
        SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm");
        map.put("schedule", schedules);
        map.put("creatUser", user.getUid());
        List<ScheduleModel> list = scheduleDao.queryLeaderActiveMe(map);
        if (list != null) {
            for (ScheduleModel schedule : list) {
                res = new ResultLeaderActivity();
                Date d = new Date(schedule.getBegin_time());
                String date = sdf.format(d);
                String datex = date.substring(5, 10);

                String date2 = date.substring(11, 16);

                String schedule_type = schedule.getSchedule_type();
                //处理  承办单位 和 出席领导
                StringBuffer takeName = new StringBuffer();
                StringBuffer owerName = new StringBuffer();
                if (list.size() > 0) {
                    for (ScheduleModel aff : list) {
                        if (!StringUtils.checkNull(aff.getUndertake())) {
                            String[] takerArr = aff.getUndertake().split(",");
                            for (int i = 0; i < takerArr.length; i++) {
                                if (!StringUtils.checkNull(takerArr[i])) {
                                    //承办单位
                                    String departName = departmentMapper.departmentOneSelect(Integer.parseInt(takerArr[i]));
                                    if (departName == null) {
                                        departName = "";
                                    } else {
                                        takeName.append(departName).append(",");
                                    }
                                }
                            }
                            aff.setTakerName(takeName.toString());
                            res.setUndertakeName(takeName.toString());
                        }
                        if (!StringUtils.checkNull(aff.getLeader())) {
                            String[] owerArr = aff.getLeader().split(",");
                            for (int i = 0; i < owerArr.length; i++) {
                                if (!StringUtils.checkNull(owerArr[i])) {
                                    //出席领导
                                    String userName = usersMapper.getUsernameByUserId(owerArr[i]);
                                    owerName.append(userName).append(",");
                                }
                            }
                            aff.setOwnerName(owerName.toString());
                            res.setAttenteeUser(owerName.toString());
                        }
                    }
                }
                //出席人员
                String attentees = schedule.getAttendee();
                String[] split = attentees.split(",");
                String attenteeNames = "";
                if (split != null && split.length > 0) {
                    for (String s : split) {
                        String name = userdao.getUsernameByUserId(s);
                        if (name != null && name != "") {
                            attenteeNames = attenteeNames + name + ",";
                        }

                    }
                }
                if (attenteeNames.length() > 0) {
                    attenteeNames = attenteeNames.substring(0, attenteeNames.length() - 1);
                }

                String userName = userdao.getUsernameById(schedule.getCreate_user());
                String status = schedule.getStatus();
                int num = Integer.parseInt(status);
                if (0 == num) {
                    status = "未审批";
                }
                if (1 == num) {
                    status = "已审批";
                }
                int hours = d.getHours();
                String str = null;
                if (hours > 12) {
                    str = "下午";
                } else {
                    str = "上午";
                }
                res.setId(schedule.getId());
                res.setDate(datex);
                res.setDateAmong(str);
                res.setTime(date2);
                res.setScheduleType(schedule_type);
                res.setSubject(schedule.getSubject());
                res.setAppUser(userName);
                res.setStatus(status);
                res.setUndertake(schedule.getUndertake());
                res.setLocation(schedule.getLocation());
                res.setAttentee(attenteeNames);
                res.setRemark(schedule.getRemark());
                result.add(res);
            }
        }
        if (result != null) {
            json.setObj(result);
            json.setMsg("ok");
            json.setFlag(0);
        }
        return json;
    }

    /**
     * 添加提醒
     *
     * @param schedule
     */
    @Async
    public void addAffairs(final ScheduleModel schedule, HttpServletRequest request) {
        final String sqlType = (String) request.getSession().getAttribute("loginDateSouse");
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        final Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);
        this.threadPoolTaskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                ContextHolder.setConsumerType("xoa" + sqlType);
                SmsBody smsBody = new SmsBody();
                Users fromUser = usersMapper.getUserByUid(schedule.getCreate_user());
                smsBody.setFromId(fromUser.getUserId());
                smsBody.setContent(users.getUserName() + "为您安排新的活动：" + schedule.getSubject());
                long beginTime = schedule.getBegin_time() / 1000;
                smsBody.setSendTime(Integer.valueOf(String.valueOf(beginTime)));
                SysCode sysCode = new SysCode();
                sysCode.setCodeName("领导活动安排");
                sysCode.setParentNo("SMS_REMIND");
                if (sysCodeMapper.getCodeNoByNameAndParentNo(sysCode) != null) {
                    smsBody.setSmsType(sysCodeMapper.getCodeNoByNameAndParentNo(sysCode).getCodeNo());
                }
                smsBody.setIsAttach("0");
                String toUserId = "";
                if (!StringUtils.checkNull(schedule.getLeader())) {
                    toUserId = schedule.getLeader() + ",";
                }
                if (!StringUtils.checkNull(schedule.getAttendee())) {
                    toUserId += schedule.getAttendee();
                }
                toUserId = StringUtils.getRemoveStr(toUserId);
                smsBody.setRemindUrl("leaderschedule/leaderDetail?id=" + schedule.getId());
                String title = "您有新的活动安排！";
                String context = "主题:" + schedule.getSubject();
                smsService.saveSms(smsBody, toUserId, "1", "0", title, context, sqlType);
            }
        });

    }

    /**
    * @author 程叶同
    * @date 2018/7/25 17:26
    * @desc  批量删除
    */
    @Override
    public BaseWrapper deleteByids(String ids) {
        BaseWrapper baseWrapper=new BaseWrapper();
        if (ids!=null&&ids!="") {
            String[] array =ids.split(",");
            int i = scheduleDao.deleteByids(array);
            if (i > 0) {
            baseWrapper.setFlag(true);
            baseWrapper.setMsg("ok");
            baseWrapper.setStatus(true);
            }
        }
        return baseWrapper;
    }
}
